<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="数据表名" prop="tableName">
        <el-input
          v-model="queryParams.tableName"
          placeholder="请输入数据表名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >清除所有过滤器</el-button
        >
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="opentagkey"
          >增加</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          >导出</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          size="mini"
          plain
          icon="el-icon-upload"
          @click="daoru"
          >批量导入</el-button
        >
      </el-col>

      <el-col :span="1.5" :key="tag.key" v-for="tag in entriesObjectsArray">
        <el-tag closable :disable-transitions="false" @close="handleClose(tag)">
          {{ getTagNameComment(tag.key) }}
          {{ tag.value.operator }}{{ tag.value.value }}
        </el-tag>
      </el-col>
    </el-row>
    <el-table
      class="tb-edit"
      highlight-current-row
      :data="tableData"
      border
      style="width: 100%"
      :height="600"
      @sort-change="handleSortChange"
      ref="table"
      @row-dblclick="t"
      @selection-change="handleSelectionChange"
    >
      <!-- v-if="col.field_name.toLowerCase().includes('url'.toLowerCase())" -->
      <el-table-column type="selection" width="55" align="center" />
      <template v-for="col in cols">
        <!-- <el-table-column
          :key="col.field_name"
          :prop="col.field_name"
          align="center"
          width="100"
          sortable
        >
          <template v-slot:header>
            <span>{{ col.comment }} </span>
          </template>
          <template slot-scope="scope">
            <image-preview
              :src="scope.row.pic_url"
              :width="40"
              :height="40"
            /> </template
        ></el-table-column> -->

        <el-table-column
          v-if="col.field_name != 'picUrl'"
          :key="col.field_name"
          :prop="col.field_name"
          align="center"
          width="160"
          sortable
        >
          <template slot="header" slot-scope="scope">
            <span>{{ scope.column }} </span>

            <FilterInput
              @filterChange="handleFilterChange($event, col.field_name)"
            />
          </template>
        </el-table-column>
      </template>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.page"
      :limit.sync="queryParams.size"
      @pagination="getList"
    />

    <el-dialog
      :visible.sync="tagkeyVisible"
      width="500px"
      append-to-body
      v-if="tagkeyVisible"
    >
      <div class="el-dialog-div">
        <el-form
          ref="form"
          :model="formData"
          label-position="top"
          :inline="true"
        >
          <el-form-item
            v-for="(item, index) in formData.libraryIdList"
            :key="index"
          >
            <el-input
              style="width: 150px"
              v-model="item.comment"
              placeholder="请输入字段名"
            ></el-input>
            <!-- <el-input
              style="width: 150px"
              v-model="item.field_name"
              placeholder="请输入字段值"
            ></el-input> -->
            <el-input
              style="width: 150px"
              v-model="item.value"
              placeholder="请输入字段值"
            ></el-input>
            <!-- <span v-if="formData.libraryIdList.length > 1">
              <el-button type="primary" size="mini" @click="addLibraryIdList"
                >新增</el-button
              >
              <el-button type="danger" size="mini" @click="delRow(item, index)"
                >删除</el-button
              >
            </span> -->
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改产品二级信息对话框 :on-change="handleChange"-->
    <el-dialog
      title="导入"
      :visible.sync="dialogVisible"
      width="500px"
      append-to-body
      v-if="dialogVisible"
    >
      <!-- 文件上传-->
      <el-form
        :model="dataForm"
        ref="dataForm"
        label-width="150px"
        @submit.native.prevent
      >
        <el-form-item label="文件：" prop="file">
          <el-upload
            class="upload-import"
            ref="uploadImport"
            :http-request="httpRequest"
            action=""
            :on-remove="handleRemove"
            :file-list="fileList"
            :limit="1"
            :on-change="handleChange"
            :auto-upload="false"
            :before-upload="beforeAvatarUpload"
          >
            <!--
            accept="application/zip,.zip" 设置接收的文件类型-->
            <el-button
              v-show="!hasFile"
              slot="trigger"
              size="small"
              type="primary"
              >选取文件</el-button
            >
            <!-- <div slot="tip" class="el-upload__tip">
          只能上传zip文件，且不超过10M
        </div> -->
          </el-upload>
          <!-- 关闭自动上传-->
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitUpload">提交</el-button>
          <!-- <el-button @click="resetForm('ruleForm')">重置</el-button> -->
          <el-button @click="dialogVisible = false">取 消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>  
  
<script>
import axios from "axios";
//--------导入token
import { getToken } from "@/utils/auth";
import FilterInput from "./FilterInput.vue";
// import { bitableoperation } from "@/api/conf/BiRuleSpecifications";
import { deleteoperation, bitableoperation } from "@/api/conf/bitableoperation";
export default {
  components: { FilterInput },
  data() {
    return {
      isEdit: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,

      hasFile: false,
      fileList: [],
      dialogVisible: false,
      pjtUrl: process.env.VUE_APP_BASE_API,
      dataForm: {
        file: null,
      },

      tagkeyVisible: false,
      formData: {
        libraryIdList: [],
      },
      //动态参数
      entriesObjectsArray: [],
      // 查询参数
      queryParams: {
        page: 1,
        size: 10,

        tableName: "bi_rule_specifications",
      },
      person: {},

      cols: [],
      tableData: [],
      total: 0,
    };
  },
  created() {
    this.getList();
  },
  watch: {
    // 监听复选框配置列所有的变化
    cols: {
      handler: function (newnew, oldold) {
        // console.log(newnew);
        this.cols = newnew;
        // 这里需要让表格重新绘制一下，否则会产生固定列错位的情况
        // console.log(new Date());
        this.$nextTick(() => {
          this.$refs.table.doLayout();
          // console.log('渲染完成时间', new Date());
        });
      },
      deep: true,
      immediate: true,
    },
  },

  methods: {
    handleUpdate() {
      let obj = {
        params: this.queryParams,
        data: {
          id: { operator: "=", value: this.ids[0] },
        },
      };
      // this.openLoading();
      bitableoperation(obj).then((response) => {
        this.t(response.data.tableData[0]);
        // this.$modal.closeLoading();
        // this.cols = response.cols ? response.cols : [];
        // this.tableData = response.tableData ? response.tableData : [];
      });
    },
    //点击某一行
    t(row, column, cell, event) {
      this.ids = [row.id];
      // console.log(row, column, cell, event);
      // console.log(JSON.stringify(column));
      // this.handleUpdate(row);
      let arr = Object.entries(row).map(([key, value]) => ({ key, value }));
      console.log(JSON.stringify(arr));
      let list = [];
      arr.forEach((item) => {
        if (item.key != "id") {
          list.push({
            comment: this.getTagNameComment(item.key),
            field_name: item.key,
            value: item.value,
          });
        }

        this.formData.libraryIdList = list;
        this.tagkeyVisible = true;
        this.isEdit = true;
      });
    },
    /** 提交按钮 */
    submitForm() {
      let fd = {};
      this.formData.libraryIdList.forEach((item) => {
        // if (item.value != "") {
        fd[item.field_name] = item.value;
        // }
      });
      if (this.isEdit == false) {
        axios
          .post(
            process.env.VUE_APP_BASE_API +
              "/conf/bitableoperation/insert?tableName=" +
              this.queryParams.tableName,
            fd,
            {
              headers: {
                header: {
                  // responseType: "blob"
                },

                Authorization: "Bearer " + getToken(),
                // "Content-Type": "multipart/form-data",
              }, //定义内容格式,很重要
              // timeout: 20000,
            }
          )
          .then((response) => {
            if (response.data.code == 200) {
              this.tagkeyVisible = false;
              this.getList();
              this.$modal.msgSuccess("增加成功");
            } else {
              this.$modal.msgError("增加失败");
            }
          });
      } else if (this.isEdit == true) {
        axios
          .put(
            process.env.VUE_APP_BASE_API +
              "/conf/bitableoperation/update?tableName=" +
              this.queryParams.tableName +
              "&idColumn=id&idValue=" +
              this.ids[0],
            fd,
            {
              headers: {
                header: {
                  // responseType: "blob"
                },

                Authorization: "Bearer " + getToken(),
                // "Content-Type": "multipart/form-data",
              }, //定义内容格式,很重要
              // timeout: 20000,
            }
          )
          .then((response) => {
            this.isEdit = false;
            if (response.data.code == 200) {
              this.tagkeyVisible = false;
              this.$modal.msgSuccess("修改成功");
              this.getList();
            } else {
              this.$modal.msgError("修改失败");
            }
          });
      }
    },
    opentagkey() {
      let list = [];
      this.cols.forEach((item) => {
        if (item.field_name != "id") {
          list.push({ ...item, value: "" });
        }
      });
      this.formData.libraryIdList = list;
      this.tagkeyVisible = true;
    },
    // 取消按钮
    cancel() {
      this.tagkeyVisible = false;
    },
    //添加库存名称
    addLibraryIdList() {
      this.formData.libraryIdList.push({ comment: "", field_name: "" });
    },
    //库存名称删除
    delRow(item, index) {
      if (this.formData.libraryIdList.length > 1) {
        this.formData.libraryIdList.splice(index, 1);
      } else {
        this.$message.warning("至少选择一项");
      }
    },
    getList() {
      let obj = {
        params: this.queryParams,
        data: this.person,
      };
      this.openLoading();
      bitableoperation(obj).then((response) => {
        this.$modal.closeLoading();
        this.cols = response.data.cols ? response.data.cols : [];
        this.tableData = response.data.tableData ? response.data.tableData : [];
        this.total = response.data.total ? response.data.total : 0;
      });
    },

    handleSortChange(column) {
      /**
  排序方向 asc 升序 desc 降序
 
private String orderDirection;*/
      switch (column.order) {
        case "ascending":
          this.queryParams.sortDirection = "asc";
          break;
        case "descending":
          this.queryParams.sortDirection = "desc";
          break;
        default:
          this.queryParams.sortDirection = null;
          break;
      }
      this.queryParams.orderBy = column.prop; //查询字段是表格中字段名字
      // this.queryParams.orderDirection = column.order;//动态取值排序顺序

      this.getList();
    },
    handleFilterChange(event, filterType) {
      this.person[filterType] = event;
      console.log(JSON.stringify(this.person));
      this.getList();
      this.entriesObjectsArray = Object.entries(this.person).map(
        ([key, value]) => ({ key, value })
      );
    },
    handleClose(tag) {
      var index = this.entriesObjectsArray.indexOf(tag);
      this.entriesObjectsArray.splice(index, 1);
      console.log(JSON.stringify(this.entriesObjectsArray));
      this.person = {};
      this.entriesObjectsArray.forEach((item) => {
        this.person[item.key] = item.value;
      });
      console.log(JSON.stringify(this.person));
      this.getList();
    },
    getTagNameComment(tagName) {
      const item = this.cols.find((col) => col.field_name.includes(tagName));
      return item ? item.comment : "";
    },

    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    resetQuery() {
      this.entriesObjectsArray = [];
      this.person = {};
      this.queryParams.sortDirection = null;
      this.queryParams.orderBy = null;
      this.getList();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      console.log(JSON.stringify(ids));
      let obj = {
        tableName: this.queryParams.tableName,
        idColumn: "id",
        idValue: ids[0],
      };

      this.$modal
        .confirm('是否确认删除编号为"' + ids + '"的数据项？')
        .then(function () {
          return deleteoperation(obj);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.downExport(
        "conf/bitableoperation/export?tableName=" + this.queryParams.tableName,
        { ...this.person },

        //   tableName
        // }
        // ...this.queryParams,
        // JSON.stringify(this.person),
        // },
        `export_${new Date().getTime()}.xlsx`
      );
    },

    //图片上传前的相关判断
    beforeAvatarUpload(file) {
      // const isJPG = file.type == 'image/jpeg' || file.type == 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 100;
      // if (!isJPG) {
      //     this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
      // }
      if (!isLt2M) {
        this.$message.error("上传导入文件大小不能超过 100MB!");
      }

      return isLt2M;
    },
    handleRemove(file, fileList) {
      if (!fileList.length) {
        this.hasFile = false;
      }
      this.dataForm.file = null;
    },
    handleChange(file, fileList) {
      if (fileList.length >= 2) {
        return;
      }
      if (fileList.length === 1) {
        this.hasFile = true;
      }
      this.dataForm.file = file;
    },
    //确定按钮
    //调用组件upload的submit方法，从而触发httpRequest方法，实现手动上传
    submitUpload() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          this.$refs.uploadImport.submit();
        }
      });
    },
    httpRequest(param) {
      // if (this.dataForm.name.length < 3) {
      //   this.$modal.msgWarning("请选择到店铺");
      //   return;
      // }
      let fd = new FormData();
      fd.append("file", param.file); // 传文件
      // fd.append("tableId", this.queryParams.tableId);
      // fd.append("brand", this.dataForm.name[0]);
      // fd.append("channel", this.dataForm.name[1]);
      //dataPar.file.raw
      console.log(JSON.stringify(fd));
      this.openLoading();
      axios
        .post(
          process.env.VUE_APP_BASE_API +
            "/conf/SysTableData/insertBatch?tableName=" +
            this.queryParams.tableName,
          fd,
          {
            headers: {
              header: { responseType: "blob" },

              Authorization: "Bearer " + getToken(),
              "Content-Type": "multipart/form-data",
            }, //定义内容格式,很重要
            // // timeout: 20000,
          }
        )
        .then((response) => {
          this.$modal.closeLoading();
          console.log(response);
          if (response.data.code == 200) {
            this.dialogVisible = false;

            this.$modal.msgSuccess("导入成功");
            this.hasFile = false;
            this.getList();
            return;
            var apply = this.noticForm.noticConfig.map((item) => item.name[0]);
            if (!apply[0].comment) {
              this.noticForm.noticConfig = [];
              response.data.forEach((item) => {
                this.noticForm.noticConfig.push({
                  name: [{ ...item }],
                });
              });
            } else {
              response.data.forEach((item) => {
                this.noticForm.noticConfig.push({
                  name: [{ ...item }],
                });
              });
            }
          } else {
            this.$modal.msgError("导入失败");
          }
        });
    },
    changecascadeList(value) {
      console.log(JSON.stringify(value));
    },
    //部门文件导入修改打开
    daoru() {
      this.dialogVisible = true;
    },
    // 打开加载层
    openLoading() {
      this.$modal.loading("正在加载，请稍候！");
    },
  },
};
</script>
<style lang="scss" scoped>
.el-dialog-div {
  height: 60vh;
  overflow-x: hidden;
}
</style>